package org.zebra.tenant.jetcache;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.SimpleCacheManager;
import com.alicp.jetcache.template.QuickConfig;
import org.zebra.tenant.TenantHelper;

import java.io.Serializable;

/**
 * @author zhanghongbin
 */
public class TenantCacheManager extends SimpleCacheManager {

    @Override
    public Cache getCache(String area, String cacheName) {
        Serializable tenantId = TenantHelper.getTenantId();
        if (tenantId != null) {
            cacheName = tenantId + ":" + cacheName;
        }
        return super.getCache(area, cacheName);
    }

    @Override
    public void putCache(String area, String cacheName, Cache cache) {
        Serializable tenantId = TenantHelper.getTenantId();
        if (tenantId != null) {
            cacheName = tenantId + ":" + cacheName;
        }
        super.putCache(area, cacheName, cache);
    }

    @Override
    public <K, V> Cache<K, V> getOrCreateCache(QuickConfig config) {
        Serializable tenantId = TenantHelper.getTenantId();
        if (tenantId != null) {
            QuickConfig.Builder builder = QuickConfig.newBuilder(tenantId + ":" + config.getName());
            builder.syncLocal(config.getSyncLocal());
            builder.cacheType(config.getCacheType());
            builder.localExpire(config.getLocalExpire());
            builder.expire(config.getExpire());
            builder.valueDecoder(config.getValueDecoder());
            builder.cacheNullValue(config.getCacheNullValue());
            builder.keyConvertor(config.getKeyConvertor());
            builder.loader(config.getLoader());
            builder.localLimit(config.getLocalLimit());
            builder.penetrationProtect(config.getPenetrationProtect());
            builder.penetrationProtectTimeout(config.getPenetrationProtectTimeout());
            builder.refreshPolicy(config.getRefreshPolicy());
            builder.useAreaInPrefix(config.getUseAreaInPrefix());
            builder.valueEncoder(config.getValueEncoder());
            config = builder.build();
        }
        return super.getOrCreateCache(config);
    }
}
